<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import {scrollLeft, scrollRight} from "@/assets/js/utils.js";
import {allCases} from "@/assets/js/all-case.ts";

const scroller1 = ref({})
const scroller2 = ref({})
let timer1 = undefined
let timer2 = undefined
const props = defineProps({
  randomIds: {type: Array, default: [], required: true},
})
const emit = defineEmits(['onItemClick'])

const state = ref({
  banner1: [],
  banner2: [],
  bannerWidth: 3000
})

const start = (itemCount) => {
  timer1 = scrollLeft(itemCount, (x) => {
    scroller1.value.style.transform = `translateX(${x}px)`
  })
  timer2 = scrollRight(itemCount, (x) => {
    scroller2.value.style.transform = `translateX(${x}px)`
  })
}

onMounted(() => {
  const half = props.randomIds.length / 2
  for (let i = 0; i < props.randomIds.length; i++) {
    if (i < half) {
      state.value.banner1.push(allCases.find(item => item.caseId === props.randomIds[i]))
    } else {
      state.value.banner2.push(allCases.find(item => item.caseId === props.randomIds[i]))
    }
  }
  setTimeout(() => {
    start(half)
  }, 1000)
  state.value.bannerWidth = window.innerWidth * 0.3 * half;
})
onUnmounted(() => {
  if (timer1) {
    clearInterval(timer1)
  }
  if (timer2) {
    clearInterval(timer2)
  }
})
const clickItem = (item) => {
  emit('onItemClick', item.caseId)
}
</script>

<template>
  <view class="column container">
    <view ref="scroller1" class="row scroller" :style="{width: `${state.bannerWidth}px`}">
      <view class="item" v-for="(item,i) in state.banner1" :key="i" @click="clickItem(item)">
        <img v-if="item.img" :src="item.img" alt=""/>
      </view>
    </view>
    <view ref="scroller2" class="row scroller" :style="{width: `${state.bannerWidth}px`}">
      <view class="item" v-for="(item,i) in state.banner2" :key="i" @click="clickItem(item)">
        <img v-if="item.img" :src="item.img" alt=""/>
      </view>
    </view>
  </view>
</template>

<style scoped>
.container {
  padding: 0;
  height: calc(100vw * (886 / 1920));

  .scroller {
    height: 50%;

    .item {
      width: 30%;
      height: 100%;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
</style>